package com.bingqing.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.bingqing.common.Result;
import com.bingqing.entity.Book;
import com.bingqing.entity.Params;
import com.bingqing.entity.Type;
import com.bingqing.exception.CustomException;
import com.bingqing.service.TypeService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * ClassName: TypeController
 * Package: com.bingqing.controller
 * Description:
 *
 * @Author liuyujie
 * @Create 2024-03-10 9:24
 * @Version 1.0
 */
@RestController
@RequestMapping("/type")
public class TypeController {
    @Resource
    TypeService typeService;

    //分页查询
    @GetMapping("/search")
    public Result findBySearch(Params params){
        PageInfo<Type> info = typeService.findBySearch(params);
        return Result.success(info);
    }

    //查询所有
    @GetMapping
    public Result findAll(){
        return Result.success(typeService.findAll());
    }

    //保存
    @PostMapping("/save")
    public Result save(@RequestBody Type type){
        if(type.getId() == null){
            typeService.add(type);
        }else{
            typeService.update(type);
        }
        return Result.success();
    }



    //删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        typeService.deleteById(id);
        return Result.success();
    }

    //批量删除
    @PostMapping("/delBatch")
    public Result delBatch(@RequestBody List<Type> list){
        for (Type type : list) {
            typeService.deleteById(type.getId());
        }
        return Result.success();
    }

    //导出报表
    @GetMapping("/export")
    public Result export(HttpServletResponse response) throws IOException {
        //1.查出所有数据
        List<Type> all = typeService.findAll();
        if(CollUtil.isEmpty(all)){
            throw new CustomException("未获取到数据");
        }
        //2.定义list
        List<Map<String,Object>> list = new ArrayList<>();
        //3.遍历list，每一行保存为map，塞入list
        for (Type type : all) {
            Map<String,Object> map = new HashMap<>();
            map.put("图书类别",type.getName());
            map.put("图书类别描述",type.getDescription());
            list.add(map);
        }
        //4.创建一个 ExcelWriter，把 list 数据用这个writer写出来（生成出来）
        ExcelWriter wr = ExcelUtil.getBigWriter();
        wr.write(list,true);

        // 5. 把这个 excel 下载下来
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String flag = System.currentTimeMillis()+"";
        response.setHeader("Content-Disposition","attachment;filename="+flag+"_type.xlsx");
        ServletOutputStream out = response.getOutputStream();
        wr.flush(out, true);
        wr.close();
        IoUtil.close(System.out);

        return Result.success();
    }

    //批量上传
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        List<Type> infoList = ExcelUtil.getReader(file.getInputStream()).readAll(Type.class);
        if(!CollUtil.isEmpty(infoList)){
            for (Type type : infoList) {
                try{
                    typeService.add(type);
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }
        return Result.success();

    }
}
